package cn.liurong.weixin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.liurong.weixin.service.MainService;

/**
 * 主controller
 * 
 * @author 刘荣
 * @date 2017年4月27日 
 * @copyright wonhigh.cn 
 */
@Controller
@RequestMapping("/wx")
public class MainController {
	@Autowired
	private MainService mainService;

	/**
	 * 微信的接入:
	 * 	1）将token、timestamp、nonce三个参数进行字典序排序
	 *	2）将三个参数字符串拼接成一个字符串进行sha1加密
	 *	3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author Administrator
	 */
	@RequestMapping(value = "/main.do", method = RequestMethod.GET)
	public void main(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("微信接入开始!");
		mainService.tokenWx(request, response);
	}

	@RequestMapping(value = "/main.do", method = RequestMethod.POST)
	public void message(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("消息处理开始！");
		ServletInputStream inputStream = request.getInputStream();

		Map<String, String> messageMap = new HashMap<String, String>();
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(inputStream);
		Element rootElement = document.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> elements = rootElement.elements();

		for (Element element : elements) {
			messageMap.put(element.getName(), element.getTextTrim());
		}

		System.out.println("返回结果为：" + messageMap);

		// 如果发送的是文字消息就返回“欢迎光临”
		if ("text".equals(messageMap.get("MsgType"))) {
			mainService.sendMessage(messageMap, request, response, "欢迎光临！");
		} else if ("image".equals(messageMap.get("MsgType"))) {
			mainService.sendImageMessage(messageMap, request, response);
		} else {
			response.getWriter().append("success");
		}
	}
}
